package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import retrofit2.Call;

public class MyDemandActivity extends AppCompatActivity {
    ArrayList<HashMap<String,String>> mapList;

    private DemandAdapter allAdapter;
    private RecyclerView alllist = null;
    LinearLayoutManager allLayoutManager = null;

    private boolean changed = false;

    ProgressDialog progressDialog;
    String type ;

    private Integer GET_CODE = 300;
    private Integer ADD_CODE = 400;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mydemand);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        alllist = (RecyclerView)findViewById(R.id.need_items);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));



        Button addDemand1 = (Button) findViewById(R.id.id_mydemand_addnew);
        addDemand1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MyDemandActivity.this, DemandNewActivity.class);
                intent.putExtra("is_new", true);
                intent.putExtra("from", "mydemand_add"  );
                startActivityForResult(intent,ADD_CODE);
            }
        });
        Button addDemand = (Button) findViewById(R.id.mydemand_add);
        addDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyDemandActivity.this, DemandNewActivity.class);
                intent.putExtra("is_new", true);
                intent.putExtra("from", "mydemand_add"  );
                startActivityForResult(intent,ADD_CODE);
            }
        });


        loadData();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }


    private AsyncTask<Void,Void,GetMyDemandResponse> task = null;
    private void loadData(){
        if(task != null)return;

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "true");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {
                progressDialog.dismiss();
                render(response);
                task = null;
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }
    private void render(GetMyDemandResponse response){

            this.setTitle("我的业务(" + response.getContent().size() + ")");

            allAdapter = new DemandAdapter(this,  response.getContent() );

            allAdapter.setChangedHandler(new DemandAdapter.Changed() {
                @Override
                public void view(Integer id,View v) {
                    getIt(id ,v);
                }


            });

            alllist.setAdapter(allAdapter);


    }

    private void getIt( final Integer curid,View v ){
        Intent intent = new Intent();
        intent.setClass(MyDemandActivity.this, DemandNewActivity.class);
        intent.putExtra("from", "mydemand"  );
        intent.putExtra("is_new",false);
        intent.putExtra("id", curid  );
        startActivityForResult(intent,GET_CODE);

//        View contentView= LayoutInflater.from(this).inflate(R.layout.demand_action, null, false);
////                    PopupWindow window=new PopupWindow(contentView);
//        final PopupWindow window=new PopupWindow(contentView, 360, 480, true);
//        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        window.setOutsideTouchable(true);
//        window.showAsDropDown(v, 100, -100);
////        window.showAsDropDown(v);
//
//        Button  viewBtn = (Button) contentView.findViewById(R.id.demand_view_comments);
//        viewBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                window.dismiss();
//                Intent intent = new Intent();
//                intent.setClass( MyDemandActivity.this, ChanceViewActivity.class);
//                intent.putExtra("id",  curid );
//                startActivity(intent);
//
//            }
//        });

//
//        Button  manageBtn = (Button) contentView.findViewById(R.id.demand_manage_relations);
//        manageBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                window.dismiss();
//                Intent intent = new Intent();
//                intent.setClass(MyDemandActivity.this, MyRelationActivity.class);
//                intent.putExtra("from", "mydemand"  );
//                intent.putExtra("keyword",   "demand:" + curid + "");
//                startActivity(intent);
//
//            }
//        });
//
//
//        Button  modifyBtn = (Button) contentView.findViewById(R.id.demand_modify);
//        modifyBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                window.dismiss();
//                Intent intent = new Intent();
//                intent.setClass(MyDemandActivity.this, DemandNewActivity.class);
//                intent.putExtra("from", "mydemand"  );
//                intent.putExtra("id", curid  );
//                startActivityForResult(intent,GET_CODE);
//
//            }
//        });

//        Button  defaultBtn = (Button) contentView.findViewById(R.id.demand_setdefault);
//        defaultBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                window.dismiss();
//                changed = true;
//                setDefaultMatch( curid );
//                Common.setProfileAttrFeedback(  MyDemandActivity.this,"demand_id",curid +"");
//            }
//        });



    }


    public  void setDefaultMatch( final Integer demand_id ){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,"demand_id",demand_id +"");
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        Common.alert(MyDemandActivity.this,response.getMessage());
                    }
                    if (response.isSuccess()){
                        loadData();
                    }
                } else {
                    Common.alert(MyDemandActivity.this,response.getMessage());
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GET_CODE  || requestCode == ADD_CODE) {

            Boolean ischanged = data.getBooleanExtra("changed", true);
            if (ischanged) {
                loadData();
                changed = true;
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
